package com.mq.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
public class OrderConsumer {

    //@Resource
    //private  RedisTemplate<String, String> redisTemplate;

    //消费者，得到预下单成功或失败的消息
    //将队列绑定到交换机
    @RabbitListener(bindings = @QueueBinding(value=@Queue("spring.topic.order.queue1")
            ,exchange =@Exchange(
            value="spring.direct.order.exchage",//交换机的名字
            ignoreDeclarationExceptions = "true",//忽略交换机创建的异常
            type= ExchangeTypes.TOPIC//交换机的类型，主题模式（发布订阅模式）
    ),key = "order.add.fail")
    )
    public void listen1(String msg, Message message, Channel channel) throws IOException {
        try {
//            String  isExis = redisTemplate.opsForValue().get(msg);
//            if(!StringUtils.isEmpty(isExis)){
//                redisTemplate.delete(isExis);
//                log.info("消费者,清理redis---"+msg);
//            }else {
//                log.info(msg+"已过期");
//            }
            log.info(msg+"已过期");
            //手动确认消息消费成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){

            System.out.println("确认模式-消息消费者1 业务处理异常");
            //手动确认消息消费失败  并且让消息重回队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }finally {
        }
    }
}
